package com.fubowen.lepton.conf

import androidx.lifecycle.LiveData
import androidx.lifecycle.MutableLiveData
import androidx.lifecycle.ViewModel
import androidx.lifecycle.viewModelScope
import com.fubowen.lepton.helper.DBHelper
import kotlinx.coroutines.flow.MutableStateFlow
import kotlinx.coroutines.flow.StateFlow
import kotlinx.coroutines.launch

class SiteConfigViewModel : ViewModel() {

    /***
     * 是否显示导航
     */
    private val navigationState = MutableStateFlow(true)
    val hasNavigation: StateFlow<Boolean> get() = navigationState
    fun changeNavigationState(state: Boolean) {
        navigationState.value = state
    }

    /***
     * 是否显示导航
     */
    private val themeState = MutableStateFlow(0)
    val themeFlow: StateFlow<Int> get() = themeState
    fun setTheme(state: Int) {
        themeState.value = state
    }

    /**
     * 搜索框在主页中的位置
     */
    private val _isBottomOfSearchEditText = MutableStateFlow(false)
    val isBottomOfSearchEditText: StateFlow<Boolean> get() = _isBottomOfSearchEditText
    fun changeSearchEditTextPosition(isBottom: Boolean) {
        _isBottomOfSearchEditText.value = isBottom
    }

    /**
     * 接收弹出菜单中按钮事件
     */
    private val _command = MutableLiveData<Command>()
    val command: LiveData<Command> get() = _command
    fun sendCommand(event: Command) {
        _command.value = event
    }

    /**
     * 接收弹出菜单中按钮事件
     */
    private val _receiveCommand = MutableLiveData<Command>()
    val receiveCommand: LiveData<Command> get() = _receiveCommand
    fun receiveCommand(event: Command) {
        _receiveCommand.value = event
    }

    /**
     * 接收弹出菜单中按钮事件
     */
    private val _expandState = MutableLiveData<Boolean>()
    val expandState: LiveData<Boolean> get() = _expandState
    fun setExpandState(state: Boolean) {
        _expandState.value = state
    }

    /**
     * 接收弹出菜单中按钮事件
     */
    private val _keyboardState = MutableLiveData<Pair<Boolean, Int>>()
    val keyboardState: LiveData<Pair<Boolean, Int>> get() = _keyboardState
    fun setKeyboardState(state: Boolean, keyboardHeight: Int = 0) {
        _keyboardState.value = Pair(state, keyboardHeight)
    }

    fun saveSetting(key: String, value: String) {
        viewModelScope.launch {
            DBHelper.db.settingDao().set(key, value)
        }
    }


    val settingCache = mutableMapOf<String, String?>()

    init {
//        viewModelScope.launch {
//            DBHelper.db.settingDao().allFlow().collect {
//                settingCache.clear()
//                for (item in it) {
//                    settingCache[item.key] = item.value
//                }
//            }
//        }
    }
}